<?php

class ControllerCfGallery extends Controller {
    
	private $error = array();
 
	public function index() 
    {
		$this->load->language('cf/gallery');

		$this->document->title = $this->language->get('heading_title');
		
		$this->load->model('cf/gallery');
		
		$this->getList();
	} 

    // --------------------------------------------------------------------
    
	public function insert() 
    {
		$this->load->language('cf/gallery');

		$this->document->title = $this->language->get('heading_title');
		
		$this->load->model('cf/gallery');
		
		if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()) {
			$this->model_cf_gallery->addGallery($this->request->post);
			
			$this->session->data['success'] = $this->language->get('text_success');

			$url = '';
			
			if (isset($this->request->get['sort'])) {
				$url .= '&sort=' . $this->request->get['sort'];
			}

			if (isset($this->request->get['order'])) {
				$url .= '&order=' . $this->request->get['order'];
			}
						
			$this->redirect(HTTPS_SERVER . 'index.php?route=cf/gallery&token=' . $this->session->data['token'] . $url);
		}

		$this->getForm();
	}

    // --------------------------------------------------------------------
    
	public function update() 
    {        
		$this->load->language('cf/gallery');

		$this->document->title = $this->language->get('heading_title');
		
		$this->load->model('cf/gallery'); 
		
		if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()) {
			$this->model_cf_gallery->editGallery($this->request->get['gallery_id'], $this->request->post);
			
			$this->session->data['success'] = $this->language->get('text_success');

			$url = '';
			
			if (isset($this->request->get['page'])) {
				$url .= '&page=' . $this->request->get['page'];
			}

			if (isset($this->request->get['sort'])) {
				$url .= '&sort=' . $this->request->get['sort'];
			}

			if (isset($this->request->get['order'])) {
				$url .= '&order=' . $this->request->get['order'];
			}
						
			$this->redirect(HTTPS_SERVER . 'index.php?route=cf/gallery&token=' . $this->session->data['token'] . $url);
		}

		$this->getForm();
	}

    // --------------------------------------------------------------------
    
	public function delete() 
    { 
		$this->load->language('cf/gallery');

		$this->document->title = $this->language->get('heading_title');
		
		$this->load->model('cf/gallery');

		if (isset($this->request->post['selected']) && $this->validateDelete()) {
			foreach ($this->request->post['selected'] as $gallery_id) {
				$this->model_cf_gallery->deleteGallery($gallery_id);
			}

			$this->session->data['success'] = $this->language->get('text_success');

			$url = '';
			
			if (isset($this->request->get['page'])) {
				$url .= '&page=' . $this->request->get['page'];
			}

			if (isset($this->request->get['sort'])) {
				$url .= '&sort=' . $this->request->get['sort'];
			}

			if (isset($this->request->get['order'])) {
				$url .= '&order=' . $this->request->get['order'];
			}
						
			$this->redirect(HTTPS_SERVER . 'index.php?route=cf/gallery&token=' . $this->session->data['token'] . $url);
		}

		$this->getList();
	}

    // --------------------------------------------------------------------
    
    /**
     * Browse images
     *
     * @return      void
     * @access      public
     */
    public function browse() 
    {        
        $this->load->language('cf/gallery');
        
        $this->document->title = $this->language->get('heading_title_2');
        $lang_items_key = 'heading_title|button_add_image|button_back|tab_image_list|text_image_manager';
        $this->data = array_merge($this->data, $this->language->gets($lang_items_key));
        
        $this->data['error_warning'] = isset($this->error['warning']) ? $this->error['warning'] : '';
        
        $url = '';
        if (isset($this->request->get['sort'])) {
            $url .= '&sort=' . $this->request->get['sort'];
        }

        if (isset($this->request->get['order'])) {
            $url .= '&order=' . $this->request->get['order'];
        }
                
        $this->document->breadcrumbs = array();

        $this->document->breadcrumbs[] = array(
            'href'      => HTTPS_SERVER . 'index.php?route=common/home&token=' . $this->session->data['token'],
            'text'      => $this->language->get('text_home'),
            'separator' => FALSE
        );

        $this->document->breadcrumbs[] = array(
            'href'      => HTTPS_SERVER . 'index.php?route=cf/gallery&token=' . $this->session->data['token'] . $url,
            'text'      => $this->language->get('heading_title'),
            'separator' => ' :: '
        );
        
        $this->document->breadcrumbs[] = array(
            'href'      => HTTPS_SERVER . 'index.php?route=cf/gallery/browse&gallery_id=' . (int)$this->request->get['gallery_id'] . '&token=' . $this->session->data['token'] . $url,
            'text'      => $this->language->get('heading_title_2'),
            'separator' => ' :: '
        );
                                           
        $this->data['cancel'] = HTTPS_SERVER . 'index.php?route=cf/gallery&token=' . $this->session->data['token'] . $url;
        $this->data['token'] = $this->session->data['token'];
        $this->data['save_image_link'] = HTTPS_SERVER . 'index.php?route=cf/gallery/save_image&token=' . $this->session->data['token'];
        $this->data['delete_image_link'] = HTTPS_SERVER . 'index.php?route=cf/gallery/delete_image&token=' . $this->session->data['token'];
        $this->data['gallery_id'] = (int)$this->request->get['gallery_id'];

        
        $this->load->model('cf/gallery');
        $this->load->model('tool/image');
        $this->data['preview'] = $this->model_tool_image->resize('no_image.jpg', 100, 100);
        
        // get all images from gallery and build their full path
        $this->data['images'] = array();
        $xp = $this->model_cf_gallery->getAllImages((int)$this->request->get['gallery_id']);        
        for ($i = 0; $i < count($xp); $i++) {
            $this->data['images'][] = array('image_id' => $xp[$i]['image_id'], 'image_full_path' => $this->model_tool_image->resize($xp[$i]['image'], 100, 100));
        }
        
        $this->template = 'cf/gallery_browse.tpl';
        $this->children = array(
            'common/header',    
            'common/footer'    
        );
        
        $this->response->setOutput($this->render(TRUE), $this->config->get('config_compression'));
    }
    
    // --------------------------------------------------------------------
    
    public function save_image()
    {
        $this->load->language('cf/gallery');
        $this->load->model('cf/gallery');
        
        $gallery_id = isset($this->request->post['gallery_id']) ? (int)$this->request->post['gallery_id'] : 0;
        $image_id   = isset($this->request->post['image_id']) ? (int)$this->request->post['image_id'] : 0;
        $image_name = isset($this->request->post['image_name']) ? $this->request->post['image_name'] : '';
        
        $ret = array('status' => 0, 'message' => $this->language->get('error_process'));
        
        if ($gallery_id > 0 && $image_name != '') {            
            $ret['message'] = $this->model_cf_gallery->saveImage($gallery_id, $image_id, $image_name);
            $ret['status'] = 1;
        }
        
        echo json_encode($ret);
    }
    
    // --------------------------------------------------------------------
    
    public function delete_image()
    {
        $this->load->language('cf/gallery');
        $this->load->model('cf/gallery');
        
        $image_id = (int)$this->request->post['id'];
        
        $ret = array('status' => 0, 'message' => $this->language->get('error_process'));
        
        if ($image_id > 0) {
            $this->model_cf_gallery->deleteImage($image_id);
            $ret['status'] = 1;
        }
        
        echo json_encode($ret);
    }
    
    // --------------------------------------------------------------------
    
    /**
     * Get full galleries list and populate data to table 
     *
     * @return
     * @access
     */
	private function getList() 
    {
        $sort = isset($this->request->get['sort']) ? $this->request->get['sort'] : 'sort_order';
        $order = isset($this->request->get['order']) ? $this->request->get['order'] : 'ASC';
        
        $url = '';
            
        if (isset($this->request->get['sort'])) {
            $url .= '&sort=' . $this->request->get['sort'];
        }

        if (isset($this->request->get['order'])) {
            $url .= '&order=' . $this->request->get['order'];
        }

        $this->document->breadcrumbs = array();

        $this->document->breadcrumbs[] = array(
            'href'      => HTTPS_SERVER . 'index.php?route=common/home&token=' . $this->session->data['token'],
            'text'      => $this->language->get('text_home'),
            'separator' => FALSE
        );

        $this->document->breadcrumbs[] = array(
            'href'      => HTTPS_SERVER . 'index.php?route=cf/gallery&token=' . $this->session->data['token'] . $url,
            'text'      => $this->language->get('heading_title'),
            'separator' => ' :: '
        );
                            
        $this->data['insert'] = HTTPS_SERVER . 'index.php?route=cf/gallery/insert&token=' . $this->session->data['token'] . $url;
        $this->data['delete'] = HTTPS_SERVER . 'index.php?route=cf/gallery/delete&token=' . $this->session->data['token'] . $url;    

        $data = array(
            'sort'  => $sort,
            'order' => $order
        );
        
        $results = $this->model_cf_gallery->getgalleries($data);
 
        foreach ($results as $result) {
            $action = array();
                        
            $action[] = array(
                'text' => $this->language->get('text_edit'),
                'href' => HTTPS_SERVER . 'index.php?route=cf/gallery/update&token=' . $this->session->data['token'] . '&gallery_id=' . $result['gallery_id'] . $url
            );            
            
            $action[] = array(
                'text' => $this->language->get('text_browse'),
                'href' => HTTPS_SERVER . 'index.php?route=cf/gallery/browse&token=' . $this->session->data['token'] . '&gallery_id=' . $result['gallery_id'] . $url
            );
                        
            $this->data['gallery'][] = array(
                'gallery_id'    => $result['gallery_id'],
                'title'         => $result['title'],
                'status'        => ($result['status'] ? $this->language->get('text_enabled') : $this->language->get('text_disabled')),
                'sort_order'    => (int) $result['sort_order'],
                'date_added' => date($this->language->get('date_format_short'), strtotime($result['date_added'])),
                'selected'   => isset($this->request->post['selected']) && in_array($result['review_id'], $this->request->post['selected']),
                'action'     => $action
            );
        }
    
        $lang_items_key = 'heading_title|text_no_results|column_title|column_status|column_date_added|column_sort_order|column_action|button_insert|button_delete';
        $this->data = array_merge($this->data, $this->language->gets($lang_items_key)); 
        
        $this->data['error_warning'] = isset($this->error['warning']) ? $this->error['warning'] : '';
        
        if (isset($this->session->data['success'])) {
            $this->data['success'] = $this->session->data['success'];
        
            unset($this->session->data['success']);
        } else {
            $this->data['success'] = '';
        }

        $url = '';
        $url .= $order == 'ASC' ? '&order=DESC' : '&order=ASC';

        $this->data['sort_title']       = HTTPS_SERVER . 'index.php?route=cf/gallery&token=' . $this->session->data['token'] . '&sort=title' . $url;
        $this->data['sort_status']      = HTTPS_SERVER . 'index.php?route=cf/gallery&token=' . $this->session->data['token'] . '&sort=status' . $url;
        $this->data['sort_date_added']  = HTTPS_SERVER . 'index.php?route=cf/gallery&token=' . $this->session->data['token'] . '&sort=date_added' . $url;
        $this->data['sort_order']       = HTTPS_SERVER . 'index.php?route=cf/gallery&token=' . $this->session->data['token'] . '&sort=sort_order' . $url;
        
        $url = '';

        if (isset($this->request->get['sort'])) {
            $url .= '&sort=' . $this->request->get['sort'];
        }
                                                
        if (isset($this->request->get['order'])) {
            $url .= '&order=' . $this->request->get['order'];
        }

        $this->data['sort'] = $sort;
        $this->data['order'] = $order;

        $this->template = 'cf/gallery_list.tpl';
        $this->children = array(
            'common/header',    
            'common/footer'    
        );
        
        $this->response->setOutput($this->render(TRUE), $this->config->get('config_compression'));
	}

    // --------------------------------------------------------------------
    
    /**
     * Get data and show HTML form
     *
     * @param
     * @return
     * @access
     */
	private function getForm() 
    {                
        $lang_items_key = 'heading_title|text_enabled|text_disabled|text_none|text_select|entry_title|entry_description|entry_status|entry_sort_order|entry_text|entry_image|'.
                          'button_save|button_cancel|tab_general|tab_data|text_image_manager|';
        $this->data = array_merge($this->data, $this->language->gets($lang_items_key));
        
 		$this->data['error_warning']     = isset($this->error['warning']) ? $this->error['warning'] : '';
 		$this->data['error_title']       = isset($this->error['title']) ? $this->error['title'] : '';
        $this->data['error_description'] = isset($this->error['description']) ? $this->error['description'] : '';
        		
		$url = '';
			
		if (isset($this->request->get['sort'])) {
			$url .= '&sort=' . $this->request->get['sort'];
		}

		if (isset($this->request->get['order'])) {
			$url .= '&order=' . $this->request->get['order'];
		}
				
   		$this->document->breadcrumbs = array();

   		$this->document->breadcrumbs[] = array(
       		'href'      => HTTPS_SERVER . 'index.php?route=common/home&token=' . $this->session->data['token'],
       		'text'      => $this->language->get('text_home'),
      		'separator' => FALSE
   		);

   		$this->document->breadcrumbs[] = array(
       		'href'      => HTTPS_SERVER . 'index.php?route=cf/gallery&token=' . $this->session->data['token'] . $url,
       		'text'      => $this->language->get('heading_title'),
      		'separator' => ' :: '
   		);
		
        // get languages
        $this->load->model('localisation/language');
        $this->data['languages'] = $this->model_localisation_language->getLanguages();
        								
		if (!isset($this->request->get['gallery_id'])) {
			$this->data['action'] = HTTPS_SERVER . 'index.php?route=cf/gallery/insert&token=' . $this->session->data['token'] . $url;
		} else {
			$this->data['action'] = HTTPS_SERVER . 'index.php?route=cf/gallery/update&token=' . $this->session->data['token'] . '&gallery_id=' . $this->request->get['gallery_id'] . $url;
		}
		
		$this->data['cancel'] = HTTPS_SERVER . 'index.php?route=cf/gallery&token=' . $this->session->data['token'] . $url;

		$this->data['token'] = $this->session->data['token'];

		if (isset($this->request->get['gallery_id']) && ($this->request->server['REQUEST_METHOD'] != 'POST')) {            
			$gallery_info = $this->model_cf_gallery->getGallery($this->request->get['gallery_id']);            
		}
		
        $this->data['status'] = isset($this->request->post['status']) 
                                ? $this->request->post['status'] : ( isset($gallery_info) ? $gallery_info['status'] : '' );
        
        $this->data['sort_order'] = isset($this->request->post['sort_order'])
                                    ? $this->request->post['sort_order'] : ( isset($gallery_info) ? $gallery_info['sort_order'] : 0 );
        
        $this->data['image'] = isset($this->request->post['image']) 
                               ? $this->request->post['image'] : ( isset($gallery_info) ? $gallery_info['image'] : '');

        $this->data['gallery'] = isset($this->request->post['gallery']) 
                                 ? $this->request->post['gallery'] : ( isset($gallery_info) ? $this->model_cf_gallery->getGalleryDetail($this->request->get['gallery_id']) : array() );
        
        $this->load->model('tool/image');
        if (isset($gallery_info) && $gallery_info['image'] && file_exists(DIR_IMAGE . $gallery_info['image'])) {
            $this->data['preview'] = $this->model_tool_image->resize($gallery_info['image'], 100, 100);
        } else {
            $this->data['preview'] = $this->model_tool_image->resize('no_image.jpg', 100, 100);
        }
                
		$this->template = 'cf/gallery_form.tpl';
		$this->children = array(
			'common/header',	
			'common/footer'	
		);
		
		$this->response->setOutput($this->render(TRUE), $this->config->get('config_compression'));
	}
	
    // --------------------------------------------------------------------
    
	private function validateForm() 
    {        
		if (!$this->user->hasPermission('modify', 'cf/gallery')) {
			$this->error['warning'] = $this->language->get('error_permission');
		}
        
        foreach ($this->request->post['gallery'] as $language_id => $value) {
            if (DEFAULT_LANG == $language_id && ((strlen(utf8_decode($value['title'])) < 1) || (strlen(utf8_decode($value['title'])) > 200))) {
                $this->error['title'][$language_id] = $this->language->get('error_title');
            }
        }
        
        return !$this->error ? TRUE : FALSE;
	}

    // --------------------------------------------------------------------
    
	private function validateDelete() 
    {
		if (!$this->user->hasPermission('modify', 'cf/news')) {
			$this->error['warning'] = $this->language->get('error_permission');
		}
                                        
		return (!$this->error) ? TRUE : FALSE;
	}	
}

?>